//
//  AYMSuggestionController.m
//  QuickCure
//
//  Created by 徐绩 on 16/5/6.
//  Copyright © 2016年 ayumi. All rights reserved.
//

#import "AYMSuggestionController.h"

@interface AYMSuggestionController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>

@end

#import "AYMSuggestionController.h"

@interface AYMSuggestionController ()
//输入的文本框
@property (nonatomic, strong) UITextView *inputTextView;
//显示还能输入的字数
@property (nonatomic,strong) UILabel *wordNumber;

@end

@implementation AYMSuggestionController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //检测字数
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChanged:) name:@"UITextViewTextDidChangeNotification" object:nil];
  
    self.title = @"意见与反馈";
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"returnCell"];
    [self setUpUI];
}

- (void)textChanged:(NSNotification*)n{
    //限制最大字数
    if (self.inputTextView.text.length >= 200) {
        self.inputTextView.text = [self.inputTextView.text substringToIndex:200];
    }
    NSInteger textViewNum=self.inputTextView.text.length;
    NSInteger lastNum=200-textViewNum;
    self.wordNumber.text=[NSString stringWithFormat:@"%ld",lastNum];
    
}

//搭建界面
-(void)setUpUI{
    
    //组头view
    UIView *mainView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenW, (screenW*0.6)+40)];
    mainView.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    self.tableView.tableHeaderView = mainView;
    
    //设置headerView
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenW, screenW*0.6)];
    topView.backgroundColor = [UIColor whiteColor];
    [mainView addSubview:topView];
    
    //添加输入文本框体
    self.inputTextView = [UITextView new];
    self.inputTextView.delegate = self;
    self.inputTextView.frame = CGRectMake(0, 0, topView.frame.size.width, topView.frame.size.height - 60);
    self.inputTextView.font = [UIFont systemFontOfSize:14];
    [topView addSubview:self.inputTextView];
    
    //3个lable 一个button
    UILabel *fLable = [[UILabel alloc]init];
    fLable.font = [UIFont systemFontOfSize:14];
    fLable.text = @"您还可以输入";
    
    //设置剩余字数的颜色
    self.wordNumber = [[UILabel alloc]init];
    self.wordNumber.textAlignment = NSTextAlignmentCenter;
    self.wordNumber.text = @"200";
    self.wordNumber.textColor = [UIColor colorWithRed:24/255.0 green:188/255.0 blue:187/255.0 alpha:1];
    
    //第3个lable
    UILabel *sLable = [[UILabel alloc]init];
    sLable.font = [UIFont systemFontOfSize:14];
    sLable.text = @"个字";
    
    
    
    //button
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 69, 31)];
    [button setImage:[UIImage imageNamed:@"dijiaofankui"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(setMag) forControlEvents:UIControlEventTouchDown];
    
    
    //欢迎联系我们
    UILabel *wecolmeLable = [[UILabel alloc]init];
    wecolmeLable.font = [UIFont systemFontOfSize:13];
    wecolmeLable.textColor = [UIColor grayColor];
    wecolmeLable.text = @"欢迎联系我们";
    
    
    
    [topView addSubview:fLable];
    [topView addSubview:sLable];
    [topView addSubview:self.wordNumber];
    [topView addSubview:button];
    
    [mainView addSubview:wecolmeLable];
    
    //设置约束
    [button makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(topView.trailing).offset(-10);
        make.bottom.equalTo(topView.bottom).offset(-10);
    }];
    [sLable makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(button.leading).offset(-10);
        make.bottom.equalTo(fLable.bottom);
    }];
    [self.wordNumber makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(sLable.leading).offset(-5);
        make.width.equalTo(31);
        make.bottom.equalTo(fLable.bottom);
    }];
    [fLable makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.wordNumber.leading).offset(-5);
        make.bottom.equalTo(topView.bottom).offset(-12);
    }];
    
   
    [wecolmeLable makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(mainView.leading).offset(20);
        make.bottom.equalTo(mainView.bottom).offset(-10);
    }];
    topView.userInteractionEnabled = YES;
    mainView.userInteractionEnabled = YES;
    
    //取消cell分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //235 235 241
    self.tableView.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
}

-(void)setMag{
    if(self.inputTextView.text.length>0){
        self.inputTextView.text=nil;
        [SVPAlertManager alertSuccessStatus:@"提交成功!"];
    }else{
        [SVPAlertManager alertErrorStatus:@"反馈不能为空,请重新输入!"];
    }
    [self.view endEditing:YES];
    
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    [self.view endEditing:YES];
}

//设置文本可以输入的范围
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    //如果有高亮且当前字数开始位置小于200时允许输入
    if (selectedRange && pos) {
        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
        
        if (offsetRange.location < 200) {
            return YES;
        }
        else
        {
            return NO;
        }
    }
    
    
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    NSInteger caninputlen = 200 - comcatstr.length;
    
    if (caninputlen >= 0)
    {
        return YES;
    }
    else
    {
        NSInteger len = text.length + caninputlen;
        //防止当text.length + caninputlen < 0时，使得rg.length过大
        NSRange rg = {0,MAX(len,0)};
        
        if (rg.length > 0)
        {
            NSString *s = @"";
            //判断文本类型
            BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
            if (asc) {
                s = [text substringWithRange:rg];
            }
            else
            {
                __block NSInteger idx = 0;
                //截取字符串
                __block NSString  *trimString = @"";
                [text enumerateSubstringsInRange:NSMakeRange(0, [text length])
                                         options:NSStringEnumerationByComposedCharacterSequences
                                      usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
                                          
                                          if (idx >= rg.length) {
                                              *stop = YES;
                                              return ;
                                          }
                                          
                                          trimString = [trimString stringByAppendingString:substring];
                                          
                                          idx++;
                                      }];
                
                s = trimString;
            }
            //rang是指从当前光标处进行替换处理会触发didchange事件
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
            //最大限制了。
            self.wordNumber.text = [NSString stringWithFormat:@"%d",0];
        }
        return NO;
    }
    
}

//动态监测
- (void)textViewDidChange:(UITextView *)textView
{
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    //是高亮部分在变，就不要计算字符了
    if (selectedRange && pos) {
        return;
    }
    
    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;
    
    if (existTextNum > 200)
    {
        //截取到最大位置的字符
        NSString *s = [nsTextContent substringToIndex:200];
        
        [textView setText:s];
    }
    
    //不显示负数
    self.wordNumber.text = [NSString stringWithFormat:@"%ld",MAX(0,200 - existTextNum)];
}
//


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"returnCell" forIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor grayColor];
    cell.textLabel.font = [UIFont systemFontOfSize:13];
    //设置箭头
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (indexPath.row == 0) {
        cell.imageView.image = [UIImage imageNamed:@"dianhua"];
        cell.textLabel.text = @"客服电话:400-633-1113";
    }else if(indexPath.row == 1){
        cell.imageView.image = [UIImage imageNamed:@"qq"];
        cell.textLabel.text = @"用户交流群:464768569";
    }
    
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==0){
        UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"是否拨打电话" message:@"110119120" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self stoneCall];
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            Log(@"客服点击了否");
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            
        }];
        [alert addAction:yesAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    if (indexPath.row==1) {
        UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"是否与QQ12345678对话" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            Log(@"群点击了是");
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            Log(@"群点击了否");
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
        }];
        [alert addAction:yesAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
-(void) stoneCall{
    UIApplication * app = [UIApplication sharedApplication];
    NSURL * url = [NSURL URLWithString:@"tel://110119120"];
    [app openURL:url];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
